
package br.unirio.bsi.dsw.AuctionSite.action;

import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMessage;

import br.unirio.bsi.dsw.AuctionSite.model.dao.GenericDAO;

import br.unirio.bsi.dsw.AuctionSite.beans.registerUserForm;
import br.unirio.bsi.dsw.AuctionSite.beans.util.copyBean;

public class registerUserAction extends org.apache.struts.action.Action 
{
  private final static String SUCCESS = "success";
  private final static String FAILURE = "failure";
    
  @Override
  public ActionForward execute(ActionMapping mapping, 
                               ActionForm form,
                               HttpServletRequest request, 
                               HttpServletResponse response) throws Exception 
  {     
    // cria a entidade do modelo com as suas especificidades
    registerUserForm ruf = new registerUserForm();
    
    copyBean.fromActionForm(ruf, form);
                          
    // pega instancia do DAO    
    GenericDAO gD = GenericDAO.getInstance( getResources(request).getMessage("DB_NAME") );

    try
    {
      // insere no banco
      gD.insert( ruf );
      
      return mapping.findForward(SUCCESS);
    }
    catch( SQLException e )
    {     
      // verifica se o login é unico por usuario
      if( e.getSQLState().equals( GenericDAO.UNIQUE_VIOLATION ) )
      {
        ActionErrors errors = new ActionErrors();        
        errors.add("Login", new ActionMessage("error.login.exists"));
        saveErrors(request, errors);        
      }
      return mapping.findForward(FAILURE);        
    }
  }
}
